package com.ruoyi.web.controller.zhishiku;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.File;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.system.service.FileService;
import com.zhishiku.filesystem.util.MinioUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

@RestController
@Slf4j
//@AllArgsConstructor
@RequestMapping("/zhishiku/file")
//@ApiOperation("")
public class FileController extends BaseController {

    @Autowired
    private FileService fileService;

    @Autowired
    private MinioUtil minioUtil;

    @PostMapping("/rename")
    public AjaxResult renameFile(@RequestParam(value = "fileId", required = true) Long fileId,
                                 @RequestParam(value = "fileName",required = false) String fileName,
                                 @RequestParam("label") String label) {
        log.info("重命名请求参数: fileId={}, fileName={}, label={}", fileId, fileName, label);
        return fileService.renameFile(fileId,fileName,label);
    }


    @GetMapping("/content")
    public ResponseEntity<String> getFileContent(@RequestParam(required = false) Long fileId,
                                                 @RequestParam(required = false) String filePath ) {
        log.info("请求参数 - fileId: {}, filePath: {}", fileId, filePath);

        try {
            if (fileId != null) {
                File file = fileService.selectFileById(fileId);
                log.info("数据库查询结果 - 文件路径: {}", file.getFilePath());
                filePath = file.getFilePath();
            }
            log.info("最终使用的文件路径: {}", filePath);

            InputStream stream = minioUtil.getFileInputStream(filePath, "zhishiku");
            String content = IOUtils.toString(stream, StandardCharsets.UTF_8);
            log.info("文件内容长度: {}", content.length());

            return ResponseEntity.ok(content);
        } catch (Exception e) {
            log.error("MinIO文件读取失败: bucket=zhishiku, path={}", filePath, e);
            return ResponseEntity.status(500).body("文件读取失败: " + e.getMessage());
        }
    }

    /**
     * 根据id查询文件信息
     */
    @ApiOperation("根据id查询文件信息")
    @GetMapping("/getFileById/{id}")
    public AjaxResult getFileById(@PathVariable("id") Long id) {
        System.out.println("jingru--------------------根据id查询文件信息--------------------- ");

        return success(fileService.selectFileById(id));
    }

    /**
     * 获取文件树列表
     */
    @GetMapping("/fileTree")
    @ApiOperation("获取文件树列表")
    public AjaxResult fileTree(File file)
    {
        return success(fileService.selectFileTreeList());
    }

    /**
     * 获取所有文件树列表
     */
    @GetMapping("/allfileTree")
    @ApiOperation("获取文件树列表")
    public AjaxResult allFileATree(File file)
    {
        return success(fileService.selectAllFileTreeList());
    }

    /**
     * 获取当前目录文件列表
     */
    @PostMapping("/list")
    @ApiOperation("查询文件列表")
    public TableDataInfo list(@RequestBody File file)
    {
        //startPage();
        return getDataTable(fileService.selectList(file));
    }

    /**
     * 文件上传接口
     */
    @PostMapping("/upload")
    @ApiOperation("上传文件/文件夹")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile[] file,
                                 @RequestParam("parentId") Long parentId,
                                 @RequestParam("security") Integer security,
                                 @RequestParam("datasetId") String datasetId) {
        System.out.println("数据集id            :  "+ datasetId);

        try {
            fileService.uploadFile(file, parentId,security,datasetId);
            return success("文件上传成功");
        } catch (IOException e) {
            return AjaxResult.error("文件上传失败: " + e.getMessage());
        }
    }

    /**
     * 文件下载接口
     */
    @GetMapping("/download/{id}")
    @ApiOperation("下载文件")
    public void downloadFile(@PathVariable Long id, HttpServletResponse response) {
        try {
            InputStream inputStream = fileService.downloadFile(id);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=" + id);
            OutputStream outputStream = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 新建文件夹
     */
    @PostMapping("/createFolder")
    @ApiOperation("新建文件夹")
    public AjaxResult createFolder(@RequestBody File file) {
        fileService.createFolder(file);
        return success("文件夹创建成功");
    }

    /**
     * 删除文件或文件夹
     */
    @DeleteMapping("/delete/{id}")
    @ApiOperation("删除文件或文件夹")
    public AjaxResult deleteFileOrFolder(@PathVariable Long id) {
        fileService.deleteFileOrFolder(id);
        return success("删除成功");
    }

    /**
     * 根据父级id查出直系子集
     */
    @GetMapping("/getChildren/{id}")
    public TableDataInfo getChildren(@PathVariable("id") Long id) {
        return getDataTable(fileService.selectChildrenFileList(id));
    }

    /**
     * 校验文件权限
     */
    @GetMapping("/checkPremission/{id}/{auth}")
    public boolean checkPremission(@PathVariable("id") Long id
                                 , @PathVariable("auth") Integer auth) {
        return fileService.checkPremission(id,auth);
    }
}
